package cn.magictodo.weblog.admin.event.subscriber.redis;

import cn.magictodo.weblog.admin.event.UpdateArticleEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_ARTICLE_DETAIL;

/**
 * @author liu
 * @since 2023-12-11 21:00
 */
@Component
@Slf4j
public class UpdateArticleRedisSubscriber implements ApplicationListener<UpdateArticleEvent> {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(UpdateArticleEvent event) {

        // 在这里处理收到的事件，可以是任何逻辑操作
        Long articleId = event.getArticleId();

        if(Boolean.TRUE.equals(redisTemplate.hasKey(REDIS_ARTICLE_DETAIL.getPrefix() + articleId)))
            redisTemplate.delete(REDIS_ARTICLE_DETAIL.getPrefix() + articleId);

        log.info("==> 更新文章对应 Redis文章详情结束，articleId: {}", articleId);
    }
}
